package com.wengzw.message.gateway.predicate;

/**
 * @author wengzw
 * @date 2022/5/1 12:26
 */

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * 自定义断言工厂
 * 参照内置断言工厂写 BeforeRoutePredicateFactory
 */
@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {

    public AgeRoutePredicateFactory() {
        super(AgeRoutePredicateFactory.Config.class);
    }

    //读取配置文件中的参数值 给他赋值到配置类中
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("minAge","maxAge");
    }

    //断言逻辑
    @Override
    public Predicate<ServerWebExchange> apply(AgeRoutePredicateFactory.Config config) {
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                //接收前台的参数
                String age = serverWebExchange.getRequest().getQueryParams().getFirst("age");
                if (StrUtil.isNotBlank(age)) {
                    int i = Integer.parseInt(age);
                    return i < config.getMaxAge() && i > config.getMinAge();
                }
                return false;
            }
        };
    }


    //配置类，用于接收配置文件中的对应参数
    @Data
    @NoArgsConstructor
    public static class Config {
        private int maxAge;
        private int minAge;
    }

}
